package com.dyna.core.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.dyna.core.convert.BeanConverter;
import com.dyna.domain.req.PageParam;
import com.dyna.domain.resp.PageResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author zhoucaiwang
 */
public class PageUtil {

    private final static String PAGE_NUM = "pageNum";
    private final static String PAGE_SIZE = "pageSize";

    private final static Integer PAGE_NUM_DEFAULT = 1;
    private final static Integer PAGE_SIZE_DEFAULT = 10;

    /**
     * 获取分页参数
     * @return PageParam
     */
    public static PageParam getPageParam() {
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        // 获取请求头中的分页参数
        String pageNumStr = httpServletRequest.getParameter(PAGE_NUM);
        String pageSizeStr = httpServletRequest.getParameter(PAGE_SIZE);
        // 设置默认分页参数
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(Convert.toInt(pageNumStr,PAGE_NUM_DEFAULT));
        pageParam.setPageSize(Convert.toInt(pageSizeStr,PAGE_SIZE_DEFAULT));
        return pageParam;
    }

    public static <S, T> PageResult<T> convertPageResult(PageResult<S> source, Class<T> targetType) {
        return convertPageResult(source, targetType, null);
    }

    public static <S, T> PageResult<T> convertPageResult(PageResult<S> source, Class<T> targetType, Consumer<T> peek) {
        if (source == null) {
            return null;
        }
        List<T> list = convertPageResult(source.getList(), targetType);
        if (peek != null) {
            list.forEach(peek);
        }
        return new PageResult<>(list, source.getTotal());
    }

    public static <S, T> List<T> convertPageResult(List<S> source, Class<T> targetType) {
        if (source == null) {
            return null;
        }
        return CollUtil.convertList(source, s -> BeanUtil.toBean(s, targetType));
    }

    public static <S, T> PageResult<T> convertPageResult(PageResult<S> source, BeanConverter<S, T> converter) {
        if (CollUtil.isEmpty(source.getList())) {
            return null;
        }
        List<T> convertedList = converter.convertList(source.getList());
        return new PageResult<>(convertedList, source.getTotal());
    }

}
